package tech.yixiyun.framework.kuafu.controller.request.param;

import tech.yixiyun.framework.kuafu.component.Component;
import tech.yixiyun.framework.kuafu.controller.request.KuafuRequest;
import tech.yixiyun.framework.kuafu.kits.JSONKit;
import tech.yixiyun.framework.kuafu.kits.StringKit;


/**
 * 请求参数值解析器，配置注解
 */
@Component
public interface IRequestParamResolver {


    /**
     * 从请求中将参数值取出来，并转化成对应类型
     * @param request 当前请求
     * @param paramDefinition 参数定义
     * @return
     */
    Object resolve(KuafuRequest request, ParamDefinition paramDefinition) ;


    /**
     * 将json字符串，转成对应参数
     * @param jsonStr
     * @param param
     * @return
     */
    default Object parseJSONToObject(String jsonStr, ParamDefinition param) {
        if (param.getParameter().getType() == String.class) {
            return jsonStr;
        }
        if (StringKit.isBlank(jsonStr)) {
            return ParamType.getDefaultValue(param.getParameter().getType());
        }
        if (param.getParamFeature().getParamType() == ParamType.COMMON) {
            return StringKit.convert(jsonStr, param.getParameter().getType());
        } else if (param.getParamFeature().getParamType() == ParamType.LIST) {
            return JSONKit.toObjectList(jsonStr, param.getParamFeature().getSubParamFeatures()[0].getClazz());
        } else if (param.getParamFeature().getParamType() == ParamType.MAP) {
            return JSONKit.toObjectMap(jsonStr, param.getParamFeature().getSubParamFeatures()[0].getClazz(),param.getParamFeature().getSubParamFeatures()[1].getClazz());
        } else if (param.getParamFeature().getParamType() == ParamType.ARRAY) {
            return JSONKit.toObjectArray(jsonStr, param.getParamFeature().getSubParamFeatures()[0].getClazz());
        } else {
            return JSONKit.toObject(jsonStr, param.getParameter().getType());
        }
    }

}
